import QtQuick
import QtQuick.Window
import QtQuick.Controls
import QtQuick.Layouts
import Qt.labs.platform
import FluentUI
import example
import "qrc:/component"
import "qrc:/global"
import "qrc:/viewmodel"

FluWindow {

    id:main_window
    title: "CoHub"
    width: 1000
    height: 640
    minimumWidth: 520
    minimumHeight: 200
    launchMode: FluWindowType.SingleTask
    appBar: undefined

    property string password: ""
    property string account: ""

    onInitArgument:
            (argument)=>{
                account = (argument.account)
                password = (argument.password)
            }

    SettingsViewModel
    {
        id:viewmodel_settings
    }

    FluEvent
    {
        id:event_checkupdate
        name: "checkUpdate"
        onTriggered:
        {
            checkUpdate(false)
        }
    }

    Component.onCompleted:
    {
        //tour.open()
        checkUpdate(true)
        FluEventBus.registerEvent(event_checkupdate)

    }

    Component.onDestruction:
    {
        FluEventBus.unRegisterEvent(event_checkupdate)
    }

    SystemTrayIcon
    {
        id:system_tray
        visible: true
        icon.source: "qrc:/res/image/cohub.ico"
        tooltip: "CoHub"
        menu: Menu
        {
            MenuItem
            {
                text: "退出"
                onTriggered:
                {
                    FluApp.exit()
                }
            }
        }
        onActivated:
            (reason)=>
            {
                if(reason === SystemTrayIcon.Trigger)
                {
                    main_window.show()
                    main_window.raise()
                    main_window.requestActivate()
                }
            }
    }

    FluContentDialog
    {
        id:dialog_close
        title:"退出"
        message:"确定要退出程序吗？"
        negativeText:"最小化"
        buttonFlags: FluContentDialogType.NegativeButton | FluContentDialogType.NeutralButton | FluContentDialogType.PositiveButton
        onNegativeClicked:
        {
            main_window.hide()
            system_tray.showMessage("友情提示","CoHub已隐藏至托盘,点击托盘可再次激活窗口");
        }
        positiveText:"退出"
        neutralText:"取消"
        onPositiveClicked:
        {
            FluApp.exit(0)
        }
    }

    Flipable
    {
        id:flipable
        anchors.fill: parent
        Item
        {
            id:page_front
            visible:true
            anchors.fill:flipable
            FluAppBar {
                id:app_bar_front
                anchors
                {
                    top: parent.top
                    left: parent.left
                    right: parent.right
                }
                darkText: Lang.dark_mode
                showDark: true
                darkClickListener:(button)=>handleDarkChanged(button)
                closeClickListener: ()=>{dialog_close.open()}
                z:7
            }
            FluNavigationView
            {
                property int clickCount: 0
                id:nav_view
                width: parent.width
                height: parent.height
                z:999
                //Stack模式，每次切换都会将页面压入栈中，随着栈的页面增多，消耗的内存也越多，内存消耗多就会卡顿，这时候就需要按返回将页面pop掉，释放内存。该模式可以配合FluPage中的launchMode属性，设置页面的启动模式
                //pageMode: FluNavigationViewType.Stack
                //NoStack模式，每次切换都会销毁之前的页面然后创建一个新的页面，只需消耗少量内存，可以配合FluViewModel保存页面数据（推荐）
                pageMode: FluNavigationViewType.NoStack
                items: ItemsOriginal
                footerItems:ItemsFooter
                navCompactWidth: 60
                cellWidth: 160
                //hideNavAppBar: true
                displayMode:FluNavigationViewType.Open
                topPadding:FluTools.isMacos() ? 20 : 0
                //displayMode:viewmodel_settings.displayMode
                logo: "qrc:/res/image/cohub.ico"
                title:"CoHub"
                autoSuggestBox:FluAutoSuggestBox
                {
                    iconSource: FluentIcons.Search
                    items: ItemsOriginal.getSearchData()
                    placeholderText: Lang.search
                    onItemClicked:
                        (data)=>
                        {
                            ItemsOriginal.startPageByItem(data)
                        }
                }
                Component.onCompleted:
                {
                    ItemsOriginal.navigationView = nav_view
                    ItemsFooter.navigationView = nav_view
                    //ItemsOriginal.paneItemMenu = nav_item_right_menu
                    //ItemsFooter.paneItemMenu = nav_item_right_menu
                    setCurrentIndex(0)
                }
            }
        }
    }

    Component
    {
        id:com_reveal
        CircularReveal
        {
            id:reveal
            target:main_window.contentItem
            anchors.fill: parent
            onAnimationFinished:
            {
                //动画结束后释放资源
                loader_reveal.sourceComponent = undefined
            }
            onImageChanged:
            {
                changeDark()
            }
        }
    }

    FluLoader
    {
        id:loader_reveal
        anchors.fill: parent
    }

    function distance(x1,y1,x2,y2)
    {
        return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))
    }

    function handleDarkChanged(button)
    {
        if(!FluTheme.enableAnimation)
        {
            changeDark()
        }
        else
        {
            loader_reveal.sourceComponent = com_reveal
            var target = main_window.contentItem
            var pos = button.mapToItem(target,0,0)
            var mouseX = pos.x
            var mouseY = pos.y
            var radius = Math.max(distance(mouseX,mouseY,0,0),distance(mouseX,mouseY,target.width,0),distance(mouseX,mouseY,0,target.height),distance(mouseX,mouseY,target.width,target.height))
            var reveal = loader_reveal.item
            reveal.start(reveal.width*Screen.devicePixelRatio,reveal.height*Screen.devicePixelRatio,Qt.point(mouseX,mouseY),radius)
        }
    }

    function changeDark()
    {
        if(FluTheme.dark)
        {
            FluTheme.darkMode = FluThemeType.Light
        }
        else
        {
            FluTheme.darkMode = FluThemeType.Dark
        }
    }

    Shortcut
    {
        sequence: "F6"
        context: Qt.WindowShortcut
        onActivated:
        {
            tour.open()
        }
    }

    FluTour
    {
        id:tour
        steps:
        [
            {title:"夜间模式",description: "这里可以切换夜间模式!",target:()=>app_bar_front.darkButton()}
        ]
    }

    FluContentDialog
    {
        property string newVerson
        property string body
        id:dialog_update
        title:"升级提示"
        //message:"CoHub目前最新版本 "+ newVerson +" -- 当前应用版本 "+AppInfo.version+" \n现在是否去下载新版本？\n\n更新内容：\n"+body
        buttonFlags: FluContentDialogType.NegativeButton | FluContentDialogType.PositiveButton
        negativeText: "取消"
        positiveText:"确定"
        onPositiveClicked:
        {
            Qt.openUrlExternally("https://gitee.com/cnu-cowork-studio/cohub-client/releases/latest")
        }
    }

    FluHttp{
            id:http
        }

    HttpCallable
    {
        id:callable
        property bool silent: true
        onStart:
        {
            console.debug("satrt check update...")
        }
        onFinish:
        {
            console.debug("check update finish")
            FluEventBus.post("checkUpdateFinish");
        }
        onSuccess:
            (result)=>
            {
                var data = JSON.parse(result)
                console.debug("current version "+AppInfo.version)
                console.debug("new version "+data.tag_name)
                if(data.tag_name !== AppInfo.version)
                {
                    dialog_update.newVerson =  data.tag_name
                    dialog_update.body = data.body
                    dialog_update.open()
                }
                else
                {
                    if(!silent)
                    {
                        showInfo("当前版本已经是最新版")
                    }
                }
            }
        onError:
            (status,errorString)=>
            {
                if(!silent)
                {
                    showError("网络异常!")
                }
                console.debug(status+";"+errorString)
            }
    }

    function checkUpdate(silent)
    {
        callable.silent = silent
        var request = http.newRequest("https://gitee.com/cnu-cowork-studio/cohub-client/releases/latest")
        http.get(request,callable);
    }

}


